package http

import (
	"context"
	"errors"
	"fmt"
	"gcp-api-proxy/pkg/log"
	"net/http"
)

type BaseReq struct {
	Header     map[string][]string
	Body       []byte
	RequestURI string
}

type BaseResp struct {
	Header     http.Header // http请求 header
	Body       []byte      // http请求 body
	StatusCode int         // http请求状态码
}

type IReqHandler interface {
	Handle(ctx context.Context, req *BaseReq) *BaseResp
	log.LoggerProxy
}

var errNotFoundHandler = errors.New("handler not found")

func processError(loggerProxy log.LoggerProxy, path string, err error) *BaseResp {
	header := map[string][]string{}
	statusCode := http.StatusInternalServerError
	header[ContentTypeHeader] = []string{DefaultContentType}
	baseResp := &BaseResp{
		Header:     header,
		Body:       []byte(fmt.Sprintf(WebhookResponseFormat, err.Error())),
		StatusCode: statusCode,
	}
	loggerProxy.GetLogger().Errorf("handle path:%s, err: %v", path, err)
	return baseResp
}

func recoveryResult() *BaseResp {
	header := map[string][]string{}
	statusCode := http.StatusInternalServerError
	header[ContentTypeHeader] = []string{DefaultContentType}
	baseResp := &BaseResp{
		Header:     header,
		Body:       []byte(fmt.Sprintf(WebhookResponseFormat, "Server Internal Error")),
		StatusCode: statusCode,
	}
	return baseResp
}
